/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;

/**
 *
 * @author defour
 */
public class MonitoringImpl extends UnicastRemoteObject implements Monitoring {

    private ArrayList<Task> tasks;
    private int cpuLoad=0;
    private int memory=0;
    private Runtime runTime = null;
    private ServerHealth serverHealth;

     MonitoringImpl() throws RemoteException {
         tasks= new ArrayList<Task>();
        runTime = Runtime.getRuntime();

    }


    public ServerHealth getServerHealth() throws RemoteException {
        doTaskList();
        doFreeMemory();
        doCpuLoad();
        //System.out.println(tasks.size());
        serverHealth = new ServerHealth(tasks, cpuLoad, memory);
        return serverHealth;
    }
    
    private boolean doTaskList() {
        boolean r = false;
        String tmp = null;
        String[] cmd={"/bin/sh",
		"-c",
		"ps -ef | awk '{print $8 \" \" $1 \" \" $2}'"};
        tmp = runCommand(cmd);        
        parseTasks(tmp);
        
        
        return true;
    }
    
    private int doFreeMemory() {
        int r = -1;
        String tmp = runCommand("cat /proc/meminfo");

        String[] ligne = tmp.split("\n");
        for (int i = 0; i < ligne.length; i++) {
            if (ligne[i].contains("MemFree")) {
                String memoryLigne[] = ligne[i].split(":");
                String[] memoryLigneContent = memoryLigne[1].split(" ");                
                memory = Integer.parseInt(memoryLigneContent[memoryLigneContent.length - 2]);
                System.out.println("Memory: "+memory);
            }
        }
        return r;
    }
    
    private int doCpuLoad() {
        int r = -1;
		/*
        String tmp = runCommand("uptime");
        String[] ligne = tmp.split("average:");        
        String[] ligneLoad = ligne[1].split(",");         
        cpuLoad = Integer.parseInt(ligneLoad[1]);        
        
		*/
		 String tmp = runCommand("cat /proc/loadavg");
		 cpuLoad = Math.round(Float.parseFloat(tmp.split(" ")[1])*100); 
		 System.out.println("CpuLoad: "+cpuLoad);
		 r=cpuLoad;
		 return r;		  
    }   

    private String runCommand(String command) {
        Process p = null;
        String r = "Erreur init runCommand";
        try {
            //Envoi de la commande
            p = runTime.exec(command);

        } catch (IOException e) {
            r = "-1 La commande n'a pas pu etre executee";
        }
        //Parsing
        if (p != null) {
            InputStream inputStream = p.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            try {
                r = "";
                String line = bufferedReader.readLine();

                while (line != null) {
                    r += line + "\n";
                    line = bufferedReader.readLine();
                }
                //Closing Stream
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();

            } catch (IOException e) {
                r = "-1";
            }
        }
        return r;
    }
     private String runCommand(String[] command) {
        Process p = null;
        String r = "Erreur init runCommand";
        try {
            //Envoi de la commande
            p = runTime.exec(command);

        } catch (IOException e) {
            r = "-1 La commande n'a pas pu etre executee";
        }
        //Parsing
        if (p != null) {
            InputStream inputStream = p.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            try {
                r = "";
                String line = bufferedReader.readLine();

                while (line != null) {
                    r += line + "\n";
                    line = bufferedReader.readLine();
                }
                //Closing Stream
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();

            } catch (IOException e) {
                r = "-1";
            }
        }
        return r;
    }

    private int getNbTask() {
        int r = 0;
        r = tasks.size();
        return r;
    }

    private Task getTask(int id) {
        return tasks.get(id);
    }

    private void parseTasks(String chaine) {
        String[] tmp = chaine.split("\n");
        System.out.println("Nombre Taches: "+tmp.length);
        String[] tab;
        for (int i = 1; i < tmp.length; i++) {
            tab = tmp[i].split(" ");           
            tasks.add(new Task(tab[0],tab[1],tab[2]));
        }
    }
}
